<template>
  <div class="youxue-index-bar">
    <!-- 索引列表 -->
    <ul class="index-list">
      <li v-for="(item, index) in indexList" :key="index">
        <!-- 标题锚点 -->
        <div :id="item.name"></div>

        <!-- 标题 -->
        <div class="name bcl-active sticky">
          {{ item.name }}
        </div>

        <!-- 内容列表 -->
        <ul class="content-list">
          <li
            class="container border-bottom pointer-bcl"
            v-for="(content, cindex) in item.contents"
            :key="cindex"
            @click="onSelect(content)"
          >
            {{ content }}
          </li>
        </ul>
      </li>
    </ul>

    <!-- 右侧菜单列表 -->
    <div class="fixed-right box box-center">
      <ul class="menu-list cl-primary text-center fz-12">
        <li
          class="pointer"
          v-for="(item, index) in indexList"
          :key="index"
          @click="onClick(item.name)"
        >
          {{ item.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: "youxue-index-bar",

  props: {
    // 索引列表
    indexList: {
      type: Array,
      default: () => [],
    },

    // 当前页面滚动高度
    scrollTop: {
      type: Number,
      default: 0,
    },
  },

  data() {
    return {
      isUni: typeof uni != "undefined",
    };
  },

  methods: {
    /**
     * 菜单点击回调
     */
    onClick(name) {
      if (this.isUni) {
        uni
          .createSelectorQuery()
          .in(this)
          .select(`#${name}`)
          .boundingClientRect((rect) => {
            uni.pageScrollTo({
              scrollTop: rect.top + this.scrollTop,
              duration: 0,
            });
          })
          .exec();
      } else {
        document.scrollingElement.scrollTop = document.querySelector(
          `#${name}`
        ).offsetTop;
      }
    },

    /**
     * 内容选择回调
     */
    onSelect(content) {
      this.$emit("select", content);
    },
  },

  install(Vue) {
    Vue.component(this.name, this);
  },
};
</script>

<style lang="scss" scoped>
.youxue-index-bar {
  height: 100%;

  .index-list {
    li {
      .name {
        padding: 5px 15px;
        padding: 10rpx 30rpx;
      }

      ul {
        li {
          &:last-child {
            border: none;
          }
        }
      }
    }
  }

  // 右侧菜单列表
  .fixed-right {
    position: fixed;
    top: 0;
    right: 0;
    height: 100%;
    z-index: 10;

    .menu-list {
      li {
        padding: 2px 15px;
        padding: 4rpx 30rpx;
      }
    }
  }
}
</style>
